<?php

class Admin_TreeNodeController extends Zend_Rest_Controller
{
    public function init()
    {
        $this->getHelper('layout')->setLayout('admin');
    }
    
    public function indexAction(){
    	echo "index"; 
    	exit;
    }
    
    public function getAction()
    {
    	$req = $this->getRequest();
    	$m = new Admin_Model_TreeNodeMapper();
    	$node = null;
    	
    	if(($id = (int)$req->getParam('id',0))>0)
    	{
			$node = $m->find($id);
		}
    	/*elseif(1==$req->getParam('r',0))
    	{
    		//not used
    		$node = $m->findRoot(true);
    	}*/
    	$this->_helper->json ( $node );
    }
    public function postAction()
    {
    	$request = $this->getRequest();
    	$parentId = (int) $request->getParam('pId',0);
    	if ($parentId>0)
    	{
    		
    		$form = new Admin_Form_Node();//Admin_Form_Node();
    		$params = $request->getParams();
    		if ($form->isValid($params))
    		{
	    		$m = new Admin_Model_TreeNodeMapper();
	    		$val = $form->getValidValues($params);
	    		$m1 = new Admin_Model_NodeConfigMapper();
	    		//$cfg = $m1->find($val['CfgId']);
	    		
	    		$node = new Admin_Model_TreeNode($val);
				//$node->setLayoutId($cfg->getLayoutId());
	    		$node->setInMenu(isset($params['InMenu'])? 1 : 0);
	    		$m->addSubNode($parentId,$node);
	    		$result = array('success'=>true, 'msg'=>'Узел добавлен', 'id'=>$node->getId());
    		}
    		else
    			$result = array('success'=>false, 'msg'=>'Данные некорректны');
    	}
    	else
    		$result = array('success'=>false, 'msg'=>'Не установлен pId');
    	$this->_helper->json($result);
    }
    public function putAction()
    {
    	$request = $this->getRequest();
    	parse_str($request->getRawBody(),$params);
    	$id = (int)$params['id'];
    	if ($id>0)
    	{
    		$form = new Admin_Form_Node();
    		if ($form->isValid($params))
    		{
	    		$m = new Admin_Model_TreeNodeMapper();
	    		$params['InMenu'] = isset($params['InMenu'])? 1 : 0;
	    		$val = $form->getValidValues($params);
	    		$node = new Admin_Model_TreeNode($val);
	    		$node->setId($id);
	    		$m->save($node,$val);
	    		$result = array('success'=>true, 'msg'=>'Узел сохранен');
    		}
    		else
    			$result = array('success'=>false, 'msg'=>'Данные некорректны');
    	}
    	else
    		$result = array('success'=>false, 'msg'=>'Не установлен id');
	    $this->_helper->json($result);
    }    
    
	public function deleteAction()
    {
    	$id = (int)$this->getRequest()->getParam('id',0);
    	$m = new Admin_Model_TreeNodeMapper();
    	$result = ($m->delete($id)>0)?  array('success'=>true, 'msg'=>'Узел удален', 'id'=>$id) : $result = array('success'=>false, 'msg'=>'Узел не удален: не задан id'); 
    	$this->_helper->json($result);
    }
    
}

